'use strict';
const Arp = require('./minio-sdk/main/AssumeRoleProvider');
const Minio = require('./minio-sdk/main/minio');
const fs = require('fs');
const path = require('path');
const util = require('util');
const AssumeRoleProvider = Arp.AssumeRoleProvider;
let config = fs.readFileSync(path.join(process.cwd() + '/public/config.json'), 'utf-8');
config = JSON.parse(config);
const { ossConfig } = config;
const client = new Minio.Client({
  endPoint: ossConfig.ip,
  port: ossConfig.port,
  useSSL: ossConfig.useSSL,
  accessKey: ossConfig.accessKey,
  secretKey: ossConfig.secretKey,
});
const getStsInfo = async () => {
  // minioClient.traceOn()
  const asRoleProvider = new AssumeRoleProvider({
    stsEndpoint: ossConfig.endpoint,
    accessKey: ossConfig.access_key,
    secretKey: ossConfig.secret_key,
    // durationSeconds: 6,
    region: ossConfig.region,
  });
  const res = await asRoleProvider.getCredentials();
  return {
    AccessKeyId: res.accessKey,
    AccessKeySecret: res.secretKey,
    SecurityToken: res.sessionToken,
  };
};
async function get(key, local_folder) {
  return await client.fGetObject(ossConfig.bucket, key, local_folder);
}
async function put(key, folderName) {
  try {
    const metaData = {
      'Content-Type': 'text/kmz',
      'Content-Language': 123,
      'X-Amz-Meta-Testing': 1234,
      example: 5678,
    };
    const result = await client.fPutObject(ossConfig.bucket, key, folderName, metaData);
    if (result.etag) {
      return {
        res: {
          status: 200,
        },
        name: key.substr(1),
        url: ossConfig.bucket_url_prefix + key.substr(1),
      };
    }
    return result;
  } catch (e) {
    console.log('失败put', e);
  }
}
async function putBuffer(name, buffer) {
  try {
    const result = await client.putObject(ossConfig.bucket, name, buffer);
    if (result.etag) {
      console.log('上传成功');
      return { name };
    }
    return;
  } catch (e) {
    console.log(e);
  }
}
// 上传整个文件夹
async function putFolder(localFolderPath, prefix = '') {
  // 读取文件夹中的所有文件和子文件夹
  const files = await util.promisify(fs.readdir)(localFolderPath);
  const bucketName = ossConfig.bucket;
  for (const file of files) {
    const filePath = localFolderPath + '/' + file;
    const fileStat = await util.promisify(fs.stat)(filePath);

    if (fileStat.isDirectory()) {
      // 递归处理子文件夹
      await putFolder(filePath, prefix + file + '/');
    } else {
      const stream = fs.createReadStream(filePath);
      const objectName = prefix + file;
      try {
        await client.putObject(bucketName, objectName, stream, fileStat.size);
        // console.log(`已上传: ${objectName}`);
      } catch (err) {
        console.error(`上传失败: ${objectName}`, err);
      }
    }
  }
}
async function getBuffer(name) {
  return new Promise(async (resolve, reject) => {
    try {
      let buffer = [];
      const dataStream = await client.getObject(ossConfig.bucket, name);
      dataStream.on('data', chunk => {
        buffer.push(chunk);
      });
      dataStream.on('end', () => {
        buffer = Buffer.concat(buffer);
        return resolve(buffer);
      });
      dataStream.on('error', err => {
        return reject(err);
      });
      return dataStream;
    } catch (e) {
      return reject(e);
    }
  });
}
async function removeObj(bucket, key) {
  try {
    await client.removeObject(bucket, key);
  } catch (err) {
    console.log('删除失败', err);
  }
}
async function removeObjs(bucket, key) {
  try {
    await client.removeObjects(bucket, key);
  } catch (err) {
    console.log('删除失败', err);
  }
}
module.exports = {
  getStsInfo,
  put,
  get,
  putBuffer,
  getBuffer,
  removeObj,
  removeObjs,
  putFolder,
};
